import Dialog from '../../../../dist/dialog/dialog';
import polyvLive from '../../../../utils/polyvlive.js';
var CryptoJS = require('../../../../utils/CryptoJS.js');
var yz_pay = require('../../../../mycomponent/yz_pay/yz_pay');
var app = getApp();
Page({
  behaviors: [yz_pay],
  /**
   * 页面的初始数据
   */
  data: {
    is_try_time: null,
    is_questionnaire_time: null,
    // 问卷调查
    questionnaire_is_open: false,
    language: '',
    goods_id: '',
    is_show: true,
    is_vshow: false,
    isVideo: true,
    isLook: true,
    is_update: false,
    is_buy: false,
    showPopup: false,
    rewardMoneyBtn: false,
    actionSheetShow: false,
    rewardBtnShow: false,
    // 打赏金额
    rewardMoney: '',
    goodTit: '',
    goodPrice: '',
    chapterNum: '',
    teacherImg: '',
    teacherName: '',
    goodsContent: '',
    chapterList: [],
    article_content: '',
    courseShare: {},
    courseData: {},
    codeUrl: '',
    vedioSrc: '',
    coverImg: '',
    active: '',
    // 章节id
    chapter_id: '',
    // 课程id
    courseId: '',
    pushGoodList: [],
    // pushGoodList: [{
    //   "id": 93,
    //   "goods_id": 206,
    //   "lecturer_id": 3,
    //   "title": "3333",
    //   "thumb": "https://dev5.yunzshop.com/attachment/images/2/2018/08/L8Ia553RrZH83rEiLocYIY3L9o5885.jpg",
    //   "price": "100.00",
    //   "has_one_lecturer": {
    //     "id": 3,
    //     "real_name": "\u6d4b\u8bd5",
    //     "mobile": "13800138000"
    //   },
    //   "course_chapter_num": 1
    // }],
    actionSheetItems: [],
    isLoding: false,
    activeNames: ['1'],
    //章节列表
    chapterdigList: [],
    // 价格权限
    vip_level_status: {},
    islive: false,
    video_err: false,
    is_playLive: false,
    live: false,
    videoErr: true,
    ios_virtual_pay: false,
    // 标签页显示的索引
    courseTabsActive: 1,

    posterShow: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options);
    this.setData({
      goods_id: options.goods_id,
      questionnaire_is_open: false
    });

    // if (options.chapter_id) {
    //   this.setData({
    //     goods_id: options.goods_id
    //   })
    // }
    this._getData();
    try {
      var value = wx.getStorageSync('ios_virtual_pay');
      if (value) {
        this.setData({
          ios_virtual_pay: value
        });
      }
    } catch (e) {
      console.log(e);
    }
    try {
      let name = wx.getStorageSync('yz_basic_info');
      this.setData({
        shopName: name.home.mailInfo.name
      });
    } catch (err) {
      console.log(e);
    }
  },
  changeLoading() {
    this.setData({
      isLoding: true
    });
  },
  videoErr() {
    wx.showToast({
      title: '视频加载出错了！',
      icon: 'none',
      duration: 2000
    });
    this.setData({
      videoErr: false
    });
  },
  setPosterShow() {
    this.setData({
      posterShow: !this.data.posterShow
    });
  },
  getQrCode() {
    var that = this;
    app._getNetWork({
      url: app.getNetAddresss('member.member.getArticleQr'),
      success: function (res) {
        if (res.data.result == 1 && !app._isTextEmpty(res.data.data)) {
          let _data = res.data.data;
          that.setData({
            codeUrl: _data
          });
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  secret(string, code, operation) {
    code = CryptoJS.MD5(code).toString();
    var iv = CryptoJS.enc.Utf8.parse(code.substring(0, 16));
    var key = CryptoJS.enc.Utf8.parse(code.substring(16));
    if (operation) {
      return CryptoJS.AES.decrypt(string, key, {
        iv: iv,
        padding: CryptoJS.pad.Pkcs7
      }).toString(CryptoJS.enc.Utf8);
    }
    return CryptoJS.AES.encrypt(string, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.Pkcs7
    }).toString();
  },
  // 点击直播请求
  addzhibo() {

    var that = this;
    app._getNetWork({
      url: app.getNetAddresss('plugin.video-demand.api.video-course-goods.get-live-info'),
      data: {
        goods_id: that.data.goods_id
      },
      success: function (res) {
        console.log(res);
        if (res.data.result == 1) {
          console.log(res.data.data);
          if (that.data.islive == true) {
            wx.showToast({
              title: '正在直播',
              icon: 'none',
              duration: 1000
            });
            return;
          }
          let info = JSON.parse(that.secret(res.data.data, 'zoQUA@257ggflNmMppKzcU7QgYyp!tU&h54VNN3u!PAU$8FxBW', true));
          console.log(info);
          that.is_onlive(info.userId, info.channelId);
          that.setData({
            islive: true
          });
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            duration: 1000
          });
          that.setData({
            is_update: true,
            is_buy: true
          });
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  // 唤起直播
  is_onlive(liveUid, liveVid) {
    wx.showLoading({
      title: '加载直播中',
      icon: 'none'
    });
    console.log();
    const liveVideoContext = wx.createLivePlayerContext('polyvLiveVideo');
    this.setData({
      islive: true,
    });
    polyvLive.getVideo({
      uid: liveUid,
      vid: liveVid,
      videoContext: liveVideoContext,
      success: (videoInfo) => {
        // set video src and poster
        console.log(videoInfo);
        this.setPlayerSrc(videoInfo);
      },
      error: (res) => {
        console.log(res.error);
      },
      onStartLive: () => {
        console.log('start live');
        wx.hideLoading();
        // set latest video src
        this.setNewPlayerSrc();
      },
      onApiStatus: (status) => {
        console.log(status);
        if (status == 'end') {
          this.setData({
            is_playLive: false,
            islive: false
          });
          wx.hideLoading();
          wx.showToast({
            title: '当前无直播',
            icon: 'none',
            duration: 1000
          });
          polyvLive.destroy();
        } else if (status == 'live') {

          this.setData({
            is_playLive: true
          });
        }
      }
    });
  },
  // 直播赋值
  setPlayerSrc(videoInfo) {
    this.setData({
      video: {
        src: videoInfo.flvSrc, // 如果播放组件为video,只能用videoInfo.src(m3u8地址)，如果为live-player则用videoInfo.flvSrc
        poster: videoInfo.poster
      },
      is_bisrc: videoInfo.src
    });
    console.log(videoInfo.src);
  },
  setNewPlayerSrc() {
    polyvLive.getNewVideo((videoInfo) => {
      this.setPlayerSrc(videoInfo);
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareTimeline() {
    var value = wx.getStorageSync('yz_uid');
    var path = '';
    if (value) {
      path = value;
    }
    return {
      title: app._isTextEmpty(this.data.courseShare.share_title) ? this.data.goodTit : this.data.courseShare.share_title,
      query: `share_tag=2&goods_id=${this.data.goods_id}&mid=${path}`,
      imageUrl: (app._isTextEmpty(this.data.courseShare.share_thumb) && this.data.courseData.has_one_goods) ? this.data.courseData.has_one_goods.thumb : this.data.courseShare.share_thumb
    };
  },
  onShareAppMessage: function (res) {
    var value = wx.getStorageSync('yz_uid');
    var path = '';
    if (value) {
      path = value;
    }

    let _title = app._isTextEmpty(this.data.courseShare.share_title) ? this.data.goodTit : this.data.courseShare.share_title;

    let _link = '/packageA/detail_v2/detail_v2?id=' + this.data.goods_id + '&mid=' + path;

    let _imgUrl = (app._isTextEmpty(this.data.courseShare.share_thumb) && this.data.courseData.has_one_goods) ? this.data.courseData.has_one_goods.thumb :
      this.data.courseShare.share_thumb;

    let _desc = this.data.courseShare.share_desc;

    return {
      title: _title,
      desc: _desc,
      imageUrl: _imgUrl,
      path: _link,
      success: function (shareTickets) {
        console.info(shareTickets + '成功');
        // 转发成功
      },
      fail: function (res) {
        console.log(res + '失败');
        // 转发失败
      },
      complete: function (res) {
        // 不管成功失败都会执行
      }
    };
  },
  _getData() {
    var that = this;
    // 初次获取数据
    app._getNetWork({
      url: app.getNetAddresss('plugin.video-demand.api.video-course-goods.get-course-goods-detail'),
      data: {
        goods_id: that.data.goods_id
      },
      success: function (res) {
        if (res.data.result === 1) {
          let _data = res.data.data;

          if (app._isTextEmpty(_data.has_many_dig_chapter) || _data.has_many_dig_chapter.length == 0) {
            Dialog.alert({
              title: '提示',
              message: '课程已下架！',
              context: that
            }).then(() => {
              // on close
              wx.navigateBack({
                delta: 1
              });
            });
            return;
          } else {
            that.setData({
              chapterdigList: _data.has_many_dig_chapter
            });
          }

          _data.has_one_goods.content = _data.has_one_goods.content.replace(/<img/gi,
            '<img style="max-width:100%;height:auto;display:block" ');

          let playCourse = '';
          let playActive = 0;
          let has_many_dig_chapter = _data.has_many_dig_chapter;
          for (let j = 0; j < has_many_dig_chapter.length; j++) {
            if (
              has_many_dig_chapter[j].has_many_chapter.length > 0 &&
              that.data.chapter_id
            ) {
              for (
                let i = 0; i < has_many_dig_chapter[j].has_many_chapter.length; i++
              ) {
                if (has_many_dig_chapter[j].has_many_chapter[i].id === Number(that.data.chapter_id)) {
                  playCourse = has_many_dig_chapter[j].has_many_chapter[i];
                  playActive = i;
                }
              }
            } else {
              playCourse = has_many_dig_chapter[j].has_many_chapter[0];
            }
          }
          that.setData({
            courseData: _data,
            rewardBtnShow: _data.is_reward,
            goodTit: _data.has_one_goods.title,
            goodPrice: _data.has_one_goods.price,
            vip_level_status: _data.has_one_goods.vip_level_status,
            chapterNum: _data.course_chapter_num,
            teacherImg: _data.has_one_lecturer && _data.has_one_lecturer.has_one_member ? _data.has_one_lecturer.has_one_member.avatar : '',
            teacherName: _data.has_one_lecturer && _data.has_one_lecturer.real_name,
            goodsContent: _data.has_one_goods.content,
            chapter_id: playCourse.id,
            isLook: playCourse.is_audition,
            courseId: _data.id,
            pushGoodList: _data.pushGoods,
            courseShare: _data.has_one_goods.has_one_share,
            live: _data.live,
            live_title: _data.live_title,
            questionnaire_time: _data.questionnaire_time,
            plugin_point_name: _data.plugin_point_name ? _data.plugin_point_name : '积分'
          });
          let sec = (_data.questionnaire_time * 1000);
          if (_data.questionnaire_is_open) {
            this.data.is_questionnaire_time = setTimeout(() => {
              if (!that.data.is_questionnaire_time) {
                return;
              }
              that.setData({
                questionnaire_is_open: _data.questionnaire_is_open
              });
            }, sec);
          }
          switch (_data.watch) {
          case 0:
            // Dialog.alert({
            // 	title: '提示',
            // 	message: '请升级会员或者购买课程',
            // 	context: that
            // }).then(() => {
            // 	// on close
            // })
            that.setData({
              is_update: false,
              is_buy: false
            });
            that.videoInit(playActive, playCourse);
            break;
          case 1:
            // 判断是否免费章节
            if (playCourse.is_audition == 1) {
              that.setData({
                is_update: false,
                is_buy: false,
                is_show: false,
                is_vshow: true
              });
              that.videoInit(playActive, playCourse);
              break;
            } else if (playCourse.is_audition == 0) {
              Dialog.alert({
                title: '提示',
                message: '请升级会员或者购买课程',
                context: that
              }).then(() => {
                // on close
              });
              that.setData({
                is_update: true,
                is_buy: true
              });
              break;
            } else {
              break;
            }
          case 2:
            that.setData({
              is_update: false,
              is_buy: false
            });
            that.videoInit(playActive, playCourse);
            break;
          case 3:
            that.setData({
              is_update: false,
              is_buy: false
            });
            that.videoInit(playActive, playCourse);
            break;
          default:
            break;
          }
        } else {
          wx.showToast({
            title: '视频加载出错',
            icon: 'none',
            duration: 1500
          });
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  videoInit(index, item) {
    this.setData({
      is_show: false,
      is_vshow: true,
      active: item.id
    });
    this.viewPermission(
      item.id,
      index,
      item.course_id,
      item.is_audition
    );
    // this.isMp4(this.data.vedioSrc)
  },
  viewPermissionBtn(e) {
    let dataset = e.currentTarget.dataset;
    let id = dataset.item.id;
    let index = dataset.index;
    let course_id = dataset.item.course_id;
    let audition = dataset.item.is_audition;
    console.log(id, index, course_id, audition);
    console.log(dataset);
    this.viewPermission(id, index, course_id, audition);
  },
  // 根据观看权限
  viewPermission(id, index, course_id, audition) {
    // id, index, address, course_id, audition
    let that = this;
    this.setData({
      is_show: true,
      is_vshow: false,
      islive: false
    });
    this.setData({
      chapter_id: id,
      active: id
    });

    let param = {
      goods_id: this.data.goods_id,
      chapter_id: id
    };
    let url = app.getNetAddresss('plugin.video-demand.api.video-course-goods.get-video-address');
    app._getNetWork({
      url: url,
      data: param,
      success: function (res) {
        if (res.data.result == 1) {
          let _data = res.data.data;
          that.viewType(_data.watch, index, _data.video_address, course_id, id, audition, _data.video_cover_address, _data.is_try, _data.try_time);
        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  viewType(type, index, address, course_id, id, audition, coverSrc, is_try, try_time) {
    if (is_try == 1 && type == 1 && audition == 1) {
      this.setData({
        is_update: false,
        is_buy: false,
        isLook: true,
        is_vshow: true,
        is_show: false
      });
      this.videoPlay(index, address, course_id, id, coverSrc);
      return;
    } else if ((type != 2 && type != 3) && is_try == 1 && try_time > 0) {
      this.setData({
        is_update: false,
        is_buy: false,
        isLook: true,
      });
      this.videoPlay(index, address, course_id, id, coverSrc);
      if (!this.data.is_try_time) {
        // 防止重复设置定时器
        this.data.is_try_time = setTimeout(() => {
          this.setData({
            islive: false,
            is_show: true,
            is_vshow: false
          });
          if (this.data.is_try_time) {
            // 防止返回还执行弹窗
            wx.showModal({
              title: '提示',
              content: '请升级会员或者购买课程',
            });
          }

          this.setData({
            is_update: true,
            is_buy: true,
            isLook: false,
            is_vshow: false,
            is_show: true
          });
        }, try_time * 1000);
      }

      return;
    }
    switch (type) {
    case 0:
      wx.showModal({
        title: '提示',
        content: '请升级会员或者购买课程',
      });
      this.setData({
        is_update: true,
        is_buy: true,
        isLook: false,
        is_vshow: false,
        is_show: true
      });
      break;
    case 1:
      if (audition == 1) {
        this.setData({
          is_update: false,
          is_buy: false,
          isLook: true,
          is_vshow: true,
          is_show: false
        });
        this.videoPlay(index, address, course_id, id, coverSrc);
        break;
      } else if (audition == 0) {
        Dialog.alert({
          title: '提示',
          message: '请升级会员或者购买课程',
          context: that
        }).then(() => {
          // on close
        });
        this.setData({
          is_update: true,
          is_buy: true,
          isLook: false
        });
        break;
      } else {
        break;
      }
    case 2:
      this.setData({
        is_update: false,
        is_buy: false,
        isLook: true
      });
      this.videoPlay(index, address, course_id, id, coverSrc);
      break;
    case 3:
      this.setData({
        is_update: false,
        is_buy: false,
        isLook: true
      });
      this.videoPlay(index, address, course_id, id, coverSrc);
      break;
    default:
      break;
    }
  },
  // 观看视频
  videoPlay(index, src, course_id, id, coverSrc) {
    console.log(index, src, course_id, id, coverSrc);
    this.setData({
      is_show: false,
      is_vshow: true,
      active: id,
      vedioSrc: src,
      coverImg: coverSrc
    });

    // 判断当前路径
    this.isMp4(this.data.vedioSrc);

    app._getNetWork({
      url: app.getNetAddresss('plugin.video-demand.api.video-demand-member.set-watch-history'),
      data: {
        course_id: course_id,
        chapter_id: id
      },
      success: function (res) {
        if (res.data.result == 1) {
          // let _data = res.data.data
          // console.log(_data)
        } else {
          // console.error(res)
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  // 判断是否MP4
  isMp4(src) {
    if (src.endsWith('.mp4')) {
      this.setData({
        isVideo: true,
        is_show: false
      });
    } else {
      this.setData({
        isVideo: false,
        is_show: false
      });
    }
  },
  study() {
    this.setData({
      is_show: false,
      is_vshow: true
    });
  },
  // 升级会员
  update() {
    if (this.data.ios_virtual_pay) {
      wx.showModal({
        title: '提示',
        content: '十分抱歉，由于相关规定，你暂时无法在这里充值！',
        confirmText: '知道了',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log(res);
          }
        }
      });
      return false;
    }
    wx.navigateTo({
      url: '/packageA/member/course/CourseMemberUpdate/CourseMemberUpdate?goods_id=' + this.data.goods_id
    });
  },
  // 立即购买
  buy() {
    if (this.data.ios_virtual_pay) {
      wx.showModal({
        title: '提示',
        content: '十分抱歉，由于相关规定，你暂时无法在这里充值！',
        confirmText: '知道了',
        showCancel: false,
        success(res) {
          if (res.confirm) {
            console.log(res);
          }
        }
      });
      return false;
    }
    if (this.data.vip_level_status && this.data.vip_level_status.status == 1) {
      wx.showToast({
        title: this.data.vip_level_status.tips,
        icon: 'none',
        duration: 1500
      });
      return false;
    }
    if (this.data.loadBtn) {
      return;
    }
    wx.navigateTo({
      url: '/packageD/buy/myOrder_v2/myOrder_v2?tag=-2&total=1&optionsId=&goodsId=' + this.data.goods_id
    });
  },
  // 跳转至我的课程
  toMyCourse() {
    wx.navigateTo({
      url: '/packageA/member/course/CourseMy/CourseMy'
    });
  },
  // 推荐商品跳转
  pushGoodGoto(val) {
    let item = val.currentTarget.dataset.item;
    wx.navigateTo({
      url: '/packageA/detail_v2/detail_v2?id=' + item.id
    });
  },
  // 选择打赏金额
  chooseMoney(e) {
    let money = e.currentTarget.dataset.money;
    this.setData({
      rewardMoney: money
    });
  },
  // 确定打赏
  confirmReward() {
    if (app._isTextEmpty(this.data.rewardMoney)) {
      wx.showToast({
        title: '请输入或选择打赏金额',
        icon: 'none',
        duration: 1500
      });
      return;
    }

    if (this.data.rewardMoney <= 0) {
      wx.showToast({
        title: '打赏金额必须大于0',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    this.getPayData();
  },
  // 获取支付类型参数
  getPayData() {
    var that = this;
    // let actionSheetItems = [];
    app._getNetWork({
      url: app.getNetAddresss('plugin.video-demand.api.lecturer-reward.pay-type'),
      success: function (res) {
        if (res.data.result === 1) {
          let btnData = res.data.data.buttons;
          that.setData({
            showPopup: false,
            btnData: btnData,
            rewardPayshow: true
          });

        } else {
          console.error(res);
        }
      },
      fail: function (res) {
        console.error(res);
      }
    });
  },
  rewardPayshowClose() {
    this.setData({
      rewardPayshow: false
    });
  },
  rewardPayCancelBtn() {
    this.setData({
      rewardPayshow: false
    });
  },

  // 支付
  payPost(e) {
    this.setData({
      rewardPayshow: false
    });
    let type, name, btn = null;
    if (e.currentTarget) {
      btn = e.currentTarget.dataset.info;
      type = e.currentTarget.dataset.info.value;
      name = e.currentTarget.dataset.info.name;
    } else {
      btn = e;
      type = e.value;
      name = e.name;
    }
    let dataJson = {
      pay_method: type,
      amount: this.data.rewardMoney,
      pay_name: name,
      trick_id: this.data.stickid,
      client_type: '2',
      goods_id: this.data.goods_id
    };

    app._getNetWork({
      url: app.getNetAddresss('plugin.video-demand.api.lecturer-reward.run-reward-pay'),
      data: dataJson,
      success: (res) => {
        if (res.data.result === 1) {
          this.handleOtherPay(btn, type, res.data.data);
          this.onClose();
        } else {
          Dialog.alert({
            title: '提示',
            message: res.data.msg
          }).then(() => {
            // on close
          });
          console.error(res);
        }
      },
      fail: (res) => {
        console.error(res);
      }
    });
  },
  moneyShow() {
    this.setData({
      showPopup: true
    });
  },
  openInputReward() {
    this.setData({
      showPopup: false,
      rewardMoneyBtn: true
    });
  },
  onClose() {
    this.setData({
      showPopup: false,
      rewardMoneyBtn: false,
      actionSheetShow: false,
      questionnaire_is_open: false
    });
  },
  goSurvey() {
    wx.navigateTo({
      url: '/packageE/questionnaire/questions/questions?goods_id=' + this.data.goods_id + '&tag=video',
    });
  },
  openActionSheet() {
    this.setData({
      showPopup: false,
      actionSheetShow: true
    });
  },
  previewImage: function (e) {
    var current = e.currentTarget.dataset.src; // 这里获取到的是一张本地的图片
    wx.previewImage({
      current: current, // 需要预览的图片链接列表
      urls: [current] // 当前显示图片的链接
    });
  },
  onChange(event) {
    this.setData({
      activeNames: event.detail
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync('langIndex');
    this.setData({
      'language': language.en
    });
    wx.setNavigationBarTitle({
      title: '课程详情'
    });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    wx.showShareMenu({
      withShareTicket: false,
      menus: ['shareAppMessage', 'shareTimeline']
    });
    this._getData();
  },
  onHide() {
    this.data.is_try_time = null;
    this.data.is_questionnaire_time = null;
    clearTimeout(this.data.is_try_time);
    clearTimeout(this.data.is_questionnaire_time);
    console.log('onHide监听小程序隐藏', this.data.is_try_time);
  },
  onUnload() {
    this.data.is_try_time = null;
    this.data.is_questionnaire_time = null;
    clearTimeout(this.data.is_try_time);
    clearTimeout(this.data.is_questionnaire_time);
    console.log('onUnload监听小程序隐藏', this.data.is_try_time);
  },
});